package nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class NioServer {
    private static List<SocketChannel> channelList = new ArrayList<>();
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocket = ServerSocketChannel.open();
        serverSocket.socket().bind(new InetSocketAddress(9000));
        // 服务端设置为非阻塞
        serverSocket.configureBlocking(false);
        System.out.println("服务器启动");
        while (true) {
            // 与客户端建立连接
            SocketChannel socketChannel = serverSocket.accept();
            if (socketChannel != null) {
                System.out.println("与客户端: " + socketChannel.getLocalAddress() + " 建立连接成功");
                // 设置 socketChannel 非阻塞
                socketChannel.configureBlocking(false);
                channelList.add(socketChannel);
            }
            // 读取数据
            Iterator<SocketChannel> iterator = channelList.iterator();
            while (iterator.hasNext()) {
                SocketChannel sc = iterator.next();
                ByteBuffer byteBuffer = ByteBuffer.allocate(20);
                int len = sc.read(byteBuffer);
                if (len > 0) {
                    System.out.println("接收到消息: " + new String(byteBuffer.array()));
                } else if (len == -1) {
                    System.out.println("客户端断开连接");
                    iterator.remove();
                }
            }
        }

    }
}
